package cn.youyeku.zsxh.db;

import java.util.List;

/**
 * Created by wings on 2016/12/20.
 */


//构建sql语句工具
public class LinkSql {
    private String sql = "";

    public LinkSql From(List<String> tables) {
        sql += String.format(" from (%s) ",listToString(tables));
        return this;
    }

    public LinkSql Select(List<String> fields) {
        sql += String.format("select %s ",listToString(fields));
        return this;

    }

    public LinkSql Where(String where) {
        sql += " " + "where" + where + " ";
        return this;
    }

    public LinkSql Insert(String table, List<String> fileds) {
        sql = String.format("insert or ignore into  %s (%s) values(%s)", table, listToString(fileds), buildValue(fileds.size()));
        return this;
    }

    public String getSql() {
        return this.sql;
    }

    public static String listToString(List<String> stringList) {
        if (stringList == null) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        boolean flag = false;
        for (String string : stringList) {
            if (flag) {
                result.append(",");
            } else {
                flag = true;
            }
            result.append(string);
        }
        return result.toString();
    }

    public String buildValue(int size) {
        String tmp = "";
        boolean flag = false;
        for (int i = 0; i < size; i++) {
            if (flag) {
                tmp += ",?";
            } else {
                flag = true;
                tmp += "?";
            }

        }
        return tmp;
    }

}
